import java.util.Arrays;
public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }
    }
    public void shiftUp(int child) {
        int parent = (child-1)/2;
        while(parent >= 0) {
            if(elem[parent] > elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }
    public void shiftDown(int parent, int usedSize) {
        //childMin用来标记parent左右孩子的最小者
        //先用childMin标记parent的左孩子，因为parent可能有左孩子没有右孩子
        int childMin = 2 * parent + 1;
        //不断向下调整
        while(childMin < usedSize) {
            //如果右孩子存在且左右孩子最小值为右孩子，则用childMin标记右孩子
            if(childMin + 1 < usedSize && elem[childMin] > elem[childMin+1]) {
                childMin = childMin + 1;
            }
            if(elem[parent] > elem[childMin]) {
                //交换值
                int tmp = elem[parent];
                elem[parent] = elem[childMin];
                elem[childMin] = tmp;
                //交换值后，还需往后调整，因为交换值可能会破坏elem[childMin]为根节点的堆结构
                parent = childMin;
                childMin = 2 * parent + 1;
            }else {
                //说明当前结构满足堆的性质
                break;
            }
        }
    }
    public void createHeap() {
        // 找倒数第一个非叶子节点，从该节点位置开始往前一直到根节点，遇到一个节点，应用向下调整
        for (int parent = (this.usedSize-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(parent,this.usedSize);
        }
    }
    public void headSort() {
        int end = usedSize-1;
        while(end > 0) {
            int tmp = elem[end];
            elem[end] = elem[0];
            elem[0]= tmp;
            shiftDown(0, end);
            end--;
        }
    }
    public void offer(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem, 2*elem.length);
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int poll() {
        if(isEmpty()) {
            return -1;
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        return tmp;
    }
    public int peek() {
        if(isEmpty()) {
            return -1;
        }
        return elem[0];
    }
}
